package com.du.quant.controller;

import com.du.quant.common.ResBean;
import com.du.quant.constant.AnalyzeStock;
import com.du.quant.dto.StockAnalysisDTO;
import com.du.quant.dto.StockQueryDTO;
import com.du.quant.entity.StockHistory;
import com.du.quant.service.StockDataService;
import com.du.quant.service.TradingAdviceService;
import com.du.quant.util.MemoryCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/trading")
@Slf4j
public class TradingController {

    @Autowired
    private StockDataService stockDataService;

    @Autowired
    private TradingAdviceService tradingAdviceService;

    @PostMapping("/analyze")
    @SuppressWarnings("unchecked")
    public ResBean<StockAnalysisDTO> analyzeStock(@Validated @RequestBody StockQueryDTO queryDTO) {
        // 计算开始结束时间
        LocalDate now = LocalDate.now();
        LocalDate start = now.minusDays(queryDTO.getDays());
        final String historyCacheKey = String.format(AnalyzeStock.CacheKey.HISTORY_RECORD_KEY, queryDTO.getStockCode(), start, now);

        try {
            StockAnalysisDTO analysisDTO = AnalyzeStock.analyzeResult.get();
            analysisDTO.setAnalyzeDays(queryDTO.getDays());

            // 获取实时数据
            StockHistory realTimeData = stockDataService.getRealTimeStockData(queryDTO.getStockCode());
            if (realTimeData != null) {
                analysisDTO.setCurrentPrice(realTimeData.getClosePrice());
                analysisDTO.setChangeRate(realTimeData.getChangeRate());
            } else {
                analysisDTO.setStockCode(queryDTO.getStockCode());
                analysisDTO.setStockName("暂未查询到该股票");
            }

            // 获取历史数据
            Object cacheObj = MemoryCache.get(historyCacheKey);
            if (Objects.isNull(cacheObj)) {
                // 查询接口
                List<com.du.quant.dto.HistoryDataDTO> historyData =
                        stockDataService.getStockHistoryData(queryDTO.getStockCode(), queryDTO.getDays());
                analysisDTO.setHistoryData(historyData);
                // 放入缓存
                MemoryCache.put(historyCacheKey, historyData, 6 * 60 * 60 * 1000L);
            } else {
                analysisDTO.setHistoryData((List<com.du.quant.dto.HistoryDataDTO>) cacheObj);
            }

            // 生成交易建议
            analysisDTO.setAdvice(tradingAdviceService.generateAdvice(analysisDTO));

            log.info("【{}】{} 已分析完成", analysisDTO.getStockName(), historyCacheKey);
            return ResBean.ok(analysisDTO);

        } catch (Exception e) {
            return ResBean.error("分析股票失败: " + e.getMessage());
        } finally {
            AnalyzeStock.analyzeResult.remove();
        }
    }

    @GetMapping("/history/{stockCode}")
    public ResBean<List<com.du.quant.dto.HistoryDataDTO>> getStockHistory(
            @PathVariable String stockCode,
            @RequestParam(defaultValue = "180") Integer days) {
        try {
            List<com.du.quant.dto.HistoryDataDTO> historyData =
                    stockDataService.getStockHistoryData(stockCode, days);
            return ResBean.ok(historyData);
        } catch (Exception e) {
            return ResBean.error("获取历史数据失败: " + e.getMessage());
        }
    }
}